﻿using System;

using Microsoft.WindowsAzure.ServiceRuntime;

namespace NougakudoCompanion.Utils
{
    public static class InstancesManagement
    {
        /// <summary>
        /// Initialize table storage and queue storage.
        /// change accesibily fro internal to public.
        /// </summary>
        static public void Initialize()
        {
            // Setting role instance data to table storage service.
            var instance = RoleEnvironment.CurrentRoleInstance.Id;
            var instanceResult = NougakudoCompanion.Commons.TableStorageHelper.SetInstance(instance,
                                                                               Environment.MachineName);
            if (!instanceResult.Item1)
            {
                Logging.Write("Faild :: Set role instance data to table (" + instanceResult.Item2 + " )");
            }

            for (var i = 0; i < 5; i++) // Add 5 times retry login for Refine role instance data.
            {
                instanceResult = NougakudoCompanion.Commons.QueueStorageHelper.SetupQueue(instance);
                if (!instanceResult.Item1)
                {
                    Logging.Write("Faild :: Set role instance data to queue (" + instanceResult.Item2 + " )");
                }
                else
                {
                    break;
                }
                System.Threading.Thread.Sleep(3000);
            }
        }

        /// <summary>
        /// Cleanup table storage and queue storage.
        /// </summary>
        static internal void Terminate()
        {
            // Delete role instance data to table storage service.
            var instance = RoleEnvironment.CurrentRoleInstance.Id;
            var instanceResult = NougakudoCompanion.Commons.TableStorageHelper.DeleteInstance(instance);
            if (!instanceResult.Item1)
            {
                Logging.Write("Faild :: Delete role instance data to table (" + instanceResult.Item2 + " )");
            }

            instanceResult = NougakudoCompanion.Commons.QueueStorageHelper.CleanupQueue(instance);
            if (!instanceResult.Item1)
            {
                Logging.Write("Faild :: Delete role instance data to queue (" + instanceResult.Item2 + " )");
            }
        }
    }
}